﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;

namespace NutriLeaf.Phone.Pages.Account.Profile
{
    public partial class Profile : PhoneApplicationPage
    {

        AccountService.UserProfile profile;
        AccountService.User user;
        Settings.Settings setting=new Settings.Settings();

        public Profile()
        {
            InitializeComponent();
        }

        private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        {
            //checking weather the user is registered
            if (setting.User==null||setting.UserProfile==null)
            {
                //get user profile.
                Settings.SettingUtility.GetUserDataCompletedEvent += new Settings.SettingUtility.GetUserDataCompleted(SettingUtility_GetUserDataCompletedEvent);
                Settings.SettingUtility.GetUserData();
            }
            else
            {
                FillUserProfile();
            }
        }

        void SettingUtility_GetUserDataCompletedEvent(bool result)
        {
            if (result)
            {
                FillUserProfile();
            }
            else
            {
                MessageBox.Show("We cant communicate witht he web service. Try restarting the application");
            }
        }

        private void FillUserProfile()
        {
            profile = setting.UserProfile;
            user = setting.User;

            //populate the details in the form
            FillPersonalUserDetails(new AccountService.UserData
            {
                profile=profile,
                user=user
            });

            FillBiometricUserDetails(new AccountService.UserData
            {
                profile = profile,
                user = user
            });

            

        }

        private void UpdateFromFacebookBtn_Click(object sender, RoutedEventArgs e)
        {
            AccountService.AccountServiceClient client = new AccountService.AccountServiceClient();
            client.UpdateUserProfileFromFacebookCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UpdateUserProfileFromFacebookCompleted);
            client.UpdateUserProfileFromFacebookAsync(setting.FacebookAccessToken);
            
        }

        void client_UpdateUserProfileFromFacebookCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                AccountService.AccountServiceClient client = new AccountService.AccountServiceClient();
                client.GetUserDataCompleted += new EventHandler<AccountService.GetUserDataCompletedEventArgs>(client_GetUserDataCompleted);
                client.GetUserDataAsync(setting.FacebookAccessToken);
            }
        }

        void client_GetUserDataCompleted(object sender, AccountService.GetUserDataCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                FillPersonalUserDetails(e.Result);

            }

        }

        private void FillBiometricUserDetails(AccountService.UserData userdata)
        {
            if (profile.CurrentWeight != null)
            {
                WeightTB.Text = profile.CurrentWeight.ToString();
            }

            if (profile.Height != null)
            {
                HeightTB.Text = profile.Height.ToString();
            }

            if (profile.ActivityLevelID != null)
            {
                ActivityCB.SelectedIndex = (int)profile.ActivityLevelID - 1;
            }

            if (setting.WeightUnits == Constants.Units.Kilograms)
            {
                WeightUnitsCB.SelectedIndex = 1;
                //convert the values
                WeightTB.Text = Core.Weight.Converter.ConvertToPounds((decimal)profile.CurrentWeight).ToString();
            }
            if (setting.WeightUnits == Constants.Units.Pounds)
            {
                WeightUnitsCB.SelectedIndex = 0;
            }
            if (setting.HeightUnits == Constants.Units.Centimeters)
            {
                HeightUnitsCB.SelectedIndex = 1;
                //convert the values
                HeightTB.Text = Core.Height.Converter.Convert((decimal)profile.Height, Core.Height.HeightUnits.Inches, Core.Height.HeightUnits.Centimeters).ToString();
            }
            if (setting.HeightUnits == Constants.Units.Inch)
            {
                HeightUnitsCB.SelectedIndex = 0;
            }
        }

        private void FillPersonalUserDetails(AccountService.UserData user)
        {
            if (!String.IsNullOrEmpty(profile.LastName))
            {
                LastNameTB.Text = profile.LastName;
            }
            if (!String.IsNullOrEmpty(profile.FirstName))
            {
                FirstNameTB.Text = profile.FirstName;
            }

            if (profile.Gender != null)
            {
                if ((bool)profile.Gender)
                {
                    MaleRB.IsChecked = true;
                }
                if (!(bool)profile.Gender)
                {
                    FemaleRB.IsChecked = true;
                }
            }

            if (profile.Birthday.HasValue)
            {
                BirthdayTB.Text = profile.Birthday.Value.ToShortDateString();
            }
        }

        //private void WeightUnitsCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    if (WeightUnitsCB.SelectedIndex == 0)
        //    {
        //        WeightTB.Text = Core.Weight.Converter.ConvertToPounds(Convert.ToDecimal(WeightTB.Text)).ToString();
        //    }
        //    if (WeightUnitsCB.SelectedIndex == 1)
        //    {
        //        WeightTB.Text = Core.Weight.Converter.ConvertToKilograms(Convert.ToDecimal(WeightTB.Text)).ToString();
        //    }
        //}

        //private void HeightUnitsCB_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    if (HeightUnitsCB.SelectedIndex == 0)
        //    {
        //        HeightTB.Text = Core.Height.Converter.Convert(Convert.ToDecimal(HeightTB.Text),Core.Height.HeightUnits.Centimeters,Core.Height.HeightUnits.Inches).ToString();
        //    }
        //    if (HeightUnitsCB.SelectedIndex == 1)
        //    {
        //        HeightTB.Text = Core.Height.Converter.Convert(Convert.ToDecimal(HeightTB.Text), Core.Height.HeightUnits.Inches, Core.Height.HeightUnits.Centimeters).ToString();
        //    }
        //}

        private void SaveProfileAppBarBtn_Click(object sender, EventArgs e)
        {
            if (ValidateDetails())
            {
                profile.FirstName = FirstNameTB.Text;
                profile.LastName = LastNameTB.Text;
                profile.Name = FirstNameTB.Text + " " + LastNameTB.Text;
                profile.Birthday = DateTime.Parse(BirthdayTB.Text);
                if ((bool)MaleRB.IsChecked)
                {
                    profile.Gender = true;
                }
                if((bool)FemaleRB.IsChecked)
                {
                    profile.Gender = false;
                }

                profile.Age = DateTime.Now.Year - DateTime.Parse(BirthdayTB.Text).Year;

                if (WeightUnitsCB.SelectedIndex == 1)
                {
                    //convert
                    profile.CurrentWeight = Convert.ToInt32(Core.Weight.Converter.ConvertToPounds(decimal.Parse(WeightTB.Text)));
                }
                else
                {
                    profile.CurrentWeight = Convert.ToInt32(WeightTB.Text);
                }

                if (HeightUnitsCB.SelectedIndex == 1)
                {
                    //convert
                    profile.Height = Convert.ToInt32(Core.Height.Converter.Convert(decimal.Parse(HeightTB.Text),Core.Height.HeightUnits.Centimeters,Core.Height.HeightUnits.Inches));
                }
                else
                {
                    profile.Height = Convert.ToInt32(HeightTB.Text);
                }

                profile.BMI = Convert.ToDouble(Core.BMI.BMI.CalculateBMI((decimal)profile.CurrentWeight, (decimal)profile.Height, Core.Height.HeightUnits.Inches, Core.Weight.WeightUnits.Pounds));

                profile.ActivityLevelID = ActivityCB.SelectedIndex + 1;

                profile.BMR = Core.BMR.BMR.CalculateBMR(Core.Gender.GenderUtility.GetGenderOnProfile(profile), (decimal)profile.CurrentWeight, Core.Weight.WeightUnits.Pounds, (decimal)profile.Height, Core.Height.HeightUnits.Inches, (int)profile.Age);

                profile.WeightCategoryID = (int)Core.BMI.BMI.CalculateWeightCategory((decimal)profile.BMI);

                profile.TotalCalorieNeedPerDay = Core.BMR.BMR.CalculateActivityCalories((int)profile.BMR, (Core.ActivityLevel.ActivityLevel)profile.ActivityLevelID);

                profile.TargetWeight = (double)Core.BMI.BMI.CalculateRecommendedWeight((decimal)profile.Height, Core.Height.HeightUnits.Inches);

                profile.DateTimeUpdated = DateTime.Now;

                setting.UserProfile = profile;
                setting.User = user;

                AccountService.AccountServiceClient client= new AccountService.AccountServiceClient();
                client.UpdateUserDataCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(client_UpdateUserDataCompleted);
                client.UpdateUserDataAsync(new AccountService.UserData
                {
                    profile=profile,
                    user=user
                });

            }
        }

        void client_UpdateUserDataCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                MessageBox.Show("Successfully saved your profile");
                NavigationService.Navigate(new Uri(Constants.Navigation.Dashboard, UriKind.RelativeOrAbsolute));
            }
            else
            {
                MessageBox.Show("Error, Please try again");
            }
        }

        private bool ValidateDetails()
        {
            if (!String.IsNullOrEmpty(FirstNameTB.Text))
            {
                if (!String.IsNullOrEmpty(LastNameTB.Text))
                {
                    if ((bool)MaleRB.IsChecked||(bool)FemaleRB.IsChecked)
                    {
                        if (!String.IsNullOrEmpty(BirthdayTB.Text))
                        {
                            DateTime birthday;
                            if (DateTime.TryParse(BirthdayTB.Text,out birthday))
                            {
                                if (!String.IsNullOrEmpty(WeightTB.Text))
                                {
                                    if (!String.IsNullOrEmpty(HeightTB.Text))
                                    {
                                        return true;
                                    }
                                    else
                                    {
                                        MessageBox.Show("Please enter your height");
                                    }
                                }
                                else
                                {
                                    MessageBox.Show("Please enter your correct weight");
                                }
                            }
                            else
                            {
                                MessageBox.Show("Please enter your correct birthday");
                            }
                        }
                        else
                        {
                            MessageBox.Show("Please enter your birthday");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Please enter your gender");
                    }
                }
                else
                {
                    MessageBox.Show("Please enter your last name");
                }
            }
            else
            {
                MessageBox.Show("Please enter your first name");
            }

            return false;
        }

    }
}